import * as common from './common.js';
import * as db from './db.js'
import {
	apiBaseUrl
} from './config.js'

// 需要登陆的，都写到这里，否则就是不需要登陆的接口
const methodsToken = [
	'addOrder',
	'getbeginMoneyUser',
	'userRecharge',
	'getOrderList',
	'addWash',
	'updateWash',
	'payment'
];

let loadingCount = 0;

function addLoading() {
	if (loadingCount == 0) {
		uni.showLoading({
			title: '加载中'
		});
	}
	loadingCount++
}

function isCloseLoading() {
	loadingCount--
	if (loadingCount == 0) {
		uni.hideLoading();
	}
}

const post = (url, data, Loading = 'true') => {
	if (Loading) {
		addLoading()
	}
	return new Promise((resolve, reject) => {
		let header = {
			'Accept': 'application/json',
			'Content-Type': 'application/json'
			// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		};

		if (methodsToken.indexOf(url) >= 0) {
			// 判断token是否存在
			// 获取用户token
			let token = db.get("token");
			if (!token) {
				common.jumpToLogin();
				return false;
			} else {
				data.token = token;
			}
		} else {
			let token = db.get("token");
			if (token) {
				data.token = token;
			}
		}

		uni.request({
			url: apiBaseUrl + url,
			data: data,
			method: 'POST',
			success: (response) => {
				const result = response.data;
				resolve(result);
			},
			complete: () => {
				if (Loading) {
					isCloseLoading()
				}
			},
			fail: (error) => {
				if (error && error.response) {
					reject(error.response);
				}
			},
		});
	})

}

const get = (url) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: apiBaseUrl + url,
			header: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
			},
			method: 'GET',
			success: (response) => {
				resolve(response.data)
			},
			fail: (error) => {
				if (error && error.response) {
					reject(error.response);
				}
			},
			complete: () => {
				setTimeout(function() {

				}, 250);
			}
		});
	})

}

/**
 * 所有的请求
 */
//用户登录
export const login = (data) => post('login', data);
//更新用户界面显示的信息
export const userInfoInit = (data) => post('userInfoInit', data, false);
//获取所有澡堂
export const getRegionAll = () => get('getRegionAll');
//获取澡堂详情
export const getRegionInfo = (data) => post('getRegionInfo', data);
//添加预约
export const addOrder = (data) => post('addOrder', data);
//获取用户余额
export const getbeginMoneyUser = (data, callback) => post('getbeginMoneyUser', data, callback);
//充值
export const userRecharge = (data, callback) => post('userRecharge', data, callback);
//获取个人预约信息
export const getOrderList = (data) => post('getOrderList', data)
//添加洗澡
export const addWash = (data) => post('addWash', data)
//完成洗澡
export const updateWash = (data) => post('updateWash', data)
//支付扣钱
export const payment = (data) => post('payment', data)